package com.zh.zcy.untils;

import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redlock分布式锁工具类-需启动3台redis
 */
//@Component
public class RedLockUtil {
//    @Autowired
    private RedissonClient redissonClient1;

//    @Autowired
    private RedissonClient redissonClient2;

//    @Autowired
    private RedissonClient redissonClient3;

    /**
     * 获取 RedLock（高性能写法）
     */
    public RLock tryRedLock(String lockKey, long waitTime, long leaseTime) {
        RLock lock1 = redissonClient1.getLock(lockKey);
        RLock lock2 = redissonClient2.getLock(lockKey);
        RLock lock3 = redissonClient3.getLock(lockKey);
        RLock redLock = new RedissonRedLock(lock1, lock2, lock3);

        try {
            // 使用 tryLock() 替代 tryLock(waitTime, leaseTime, TimeUnit) 避免重复参数传递
            boolean acquired = redLock.tryLock(waitTime, leaseTime, TimeUnit.MILLISECONDS);
            return acquired ? redLock : null;  // 返回锁对象或 null
        } catch (InterruptedException e) {
            //等待锁时，被外部调用Thread.interrupt()主动中断时，用来重新标记中断
            Thread.currentThread().interrupt();
            return null;
        }
    }

    /**
     * 释放锁（增强健壮性）
     */
    public void releaseRedLock(RLock redLock) {
        if (redLock != null) {
            try {
                redLock.unlock();
            } catch (IllegalMonitorStateException e) {
                // 锁已自动过期，无需处理
            }
        }
    }
}
